<template>
    <div class="deploy-wrap mb10">
        <!-- <Alert type="warning" show-icon
            >提示：本步骤是对模板中的设备进行编辑，操作步骤：部署科研环境 > 进入虚拟机(操作) > 关机 >
            生成镜像 > 设置接入机器 > 保存，如不需要则点击“下一步”继续即可
        </Alert> -->
        <WarningTip placement="right">
            <p>本步骤是对模板中的设备进行编辑，如不需要则点击“下一步”继续即可，操作步骤如下：</p>
            <p>1、部署科研环境</p>
            <p>2、进入虚拟机(操作)</p>
            <p>3、关机</p>
            <p>4、生成镜像</p>
            <p>5、设置接入机器</p>
            <p>6、保存</p>
        </WarningTip>
        <!-- <Steps :current="step" class="mt10 mb10">
            <Step title="开始"></Step>
            <Step title="部署"></Step>
            <Step title="生成镜像"></Step>
            <Step title="完成"></Step>
        </Steps> -->
        <div class="controlBtn flex-between">
            <div class="flex">
                <Button
                    type="primary"
                    @click="deployExper()"
                    :loading="creatLoading"
                    :disabled="deployStatus == 3"
                    class="mt10 mb10"
                    >{{ createdVmText }}</Button
                >
                <Icon
                    type="ios-alert-outline"
                    class="deployErrorBtn ml10"
                    title="点击查看错误详情"
                    @click="getProjectDeployDetail"
                    v-if="createdVmText == '重新部署' || errorMessage"
                    style="font-size: 24px; color: #ed4014"
                />
                <Poptip confirm title="确定要销毁科研环境吗？" @on-ok="destroyExper()" class="ml10">
                    <Button type="error" v-show="![0, 10].includes(deployStatus) && deployStatus"
                        >销毁科研环境</Button
                    >
                </Poptip>
            </div>
            <div class="flex">
                <span class="destoryTime mr10" v-if="destroyStatus && proId && leftTime > 0"
                    >环境销毁倒计时：{{ curTime.h }}:{{ curTime.m }}:{{ curTime.s }}</span
                >
                <!-- <Poptip
                    confirm
                    title="每次延长时间为24个小时，确认延长销毁时间?"
                    @on-ok="extendDestroyTime"
                    v-if="destroyStatus && proId && leftTime > 0"
                    transfer
                    word-wrap
                    width="200"
                >
                    <Button type="primary">延长销毁时间</Button>
                </Poptip> -->
            </div>
        </div>
        <Progress :percent="deployProcess" :stroke-width="16" text-inside v-if="deployStatus == 9">
            <Icon type="checkmark-circled"></Icon>
            <span>{{ processText }}</span>
        </Progress>
        <EnvironManage
            :prjId="proId"
            v-if="proId && deployStatus == 3 && currentStep === 2"
            @setImageList="getImageList"
        ></EnvironManage>
        <ImageList
            ref="imageList"
            v-if="proId && currentStep === 2"
            style="margin-top: 30px"
        ></ImageList>
        <SaveExper @getExperStatus="getExperStatus"></SaveExper>
        <Modal
            v-model="deployErrorDetailModal"
            title="环境部署错误详情"
            :width="errorDetailData.length > 0 ? 80 : 20"
            footer-hide
        >
            <h3 v-if="errorMessage && errorDetailData.length == 0" style="color: #ed4014">
                {{ errorMessage }}
            </h3>
            <Table
                :columns="errorDetailColumns"
                :data="errorDetailData"
                v-if="errorDetailData.length > 0"
            ></Table>
        </Modal>
    </div>
</template>
<script>
import encryption from '@/libs/encryption.js';
import {
    deployScientificProject,
    destroyScientificProject,
    queryDeployProgress,
    selectStatus,
    queryDestroyTime,
} from '@/api/scientific/environment.js';
import { getProjectDeployDetail, queryProjectstatus } from '@/api/deploy.js';
import EnvironManage from './environManage';
import ImageList from './createImageList';
import SaveExper from './saveExper';
import WarningTip from '@/components/common/warning-tip';
export default {
    components: {
        EnvironManage,
        ImageList,
        SaveExper,
        WarningTip,
    },
    inject: ['detailParent'],
    // props: ['ecId', 'ecName', 'templateId', 'contentDetail'],
    data() {
        return {
            // 用户信息
            //userName:'',
            USER_ID: '',
            //部署信息
            proId: '', //工程id
            deployProcess: 0, //部署进度
            deployStatus: 0, //部署状态
            processText: '',
            creatLoading: false, //部署按钮loading
            btnType: 'primary', //部署按钮类型
            createdVmText: '部署科研环境', //部署按钮显示
            //销毁
            destroyLoading: false, //销毁按钮loading
            destroyStatus: false, //销毁状态
            //定时器
            queryStatus: '',
            destroyInterval: '',
            //倒计时
            leftTime: 0,
            curTime: {
                h: '00',
                m: '00',
                s: '00',
            },
            //部署错误详情
            deployErrorDetailModal: false,
            errorDetailData: [],
            errorDetailColumns: [
                {
                    key: 'name',
                    title: '名称',
                },
                {
                    key: 'type',
                    title: '类型',
                },
                {
                    key: 'status',
                    title: '状态',
                },
                {
                    key: 'operation',
                    title: '操作',
                },
                {
                    key: 'errorMsg',
                    title: '错误信息',
                },
            ],
            errorMessage: '',
        };
    },
    computed: {
        // step() {
        //     let step = 0;
        //     if (this.deployStatus === 3) {
        //         step = 1;
        //     } else if (this.generateImageList.length > 0) {
        //         step = 2;
        //     } else if (this.replaceTotal > 0) {
        //         step = 3;
        //     }
        //     return step;
        // },
        currentStep() {
            return this.detailParent.currentStep;
        },
        ecId() {
            return this.detailParent.contentDetail.id;
        },
    },
    created() {
        // 获取用户id
        let November = sessionStorage.getItem('November');
        November = JSON.parse(encryption.SelfUseDecrypt(November));
        this.USER_ID = November.userId;
        this.isRootDesigner = November.isRootDesigner;
    },
    mounted() {
        this.getExperStatus();
    },
    beforeRouteLeave(to, from, next) {
        if (to.path === '/experiment') {
            //              to.query.page = this.$route.query.page
            next();
        } else {
            next();
        }
    },
    beforeDestroy() {
        clearInterval(this.destroyInterval);
        clearInterval(this.queryStatus);
    },
    methods: {
        //调用部署接口
        deployExper() {
            let formData = {
                id: this.ecId,
                userId: this.USER_ID,
            };
            this.creatLoading = true;
            if (this.destroyInterval) {
                clearInterval(this.destroyInterval);
            }
            deployScientificProject(formData)
                .then(({ code, data: { projectId }, message }) => {
                    if (code === 1) {
                        this.proId = projectId;
                        this.detailParent.contentDetail.prjId = projectId;
                        this.queryCreatedStatus();
                        // if (res.attribute.status && res.attribute.status === 3) {
                        //     this.$Message.info('已有环境部署成功，请先销毁才能部署新的环境');
                        // } else {
                        //     this.proId = projectId;
                        //     this.queryCreatedStatus();
                        // }
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 3,
                        });
                        this.creatLoading = false;
                    }
                })
                .catch((err) => {
                    this.creatLoading = false;
                    console.log(err);
                });
        },
        // 查询部署状态
        queryCreatedStatus() {
            this.queryStatus = setInterval(() => {
                queryDeployProgress(this.proId, this.ecId)
                    .then(({ code, data: { progress, status } }) => {
                        if (code == 1) {
                            this.processText = '部署中...' + progress + '%';
                            this.deployProcess = progress;
                            this.deployStatus = status;
                            this.detailParent.updateDetail({ deployStatus: this.deployStatus });
                            // this.$emit('setDeployStatus', this.deployStatus);
                            if (progress === 100 && status === 3) {
                                this.creatLoading = false;
                                // 创建按钮
                                this.createdVmText = '部署成功';
                                this.btnType = 'primary';
                                // 销毁按钮
                                this.destroyStatus = true;
                                this.deployNum = 3;
                                //清除定时查询
                                clearInterval(this.queryStatus);
                                this.$Message.success({
                                    content: '部署成功',
                                    duration: 3,
                                });
                                setTimeout(() => {
                                    this.getDestroyTimeInter();
                                }, 3000);
                            } else if (progress === 100 && status === 6) {
                                this.creatLoading = false;
                                // 按钮颜色 文字
                                this.btnType = 'primary';
                                this.createdVmText = '重新部署';
                                // 显示销毁按钮
                                this.destroyWidth = '30%';
                                this.destroyStatus = true;
                                this.deployNum = 6;
                                //清除定时查询
                                clearInterval(this.queryStatus);
                                this.getProjectInfo(); //查询错误信息
                            }
                        } else {
                            this.creatLoading = false;
                            // 按钮颜色 文字
                            this.btnType = 'primary';
                            this.createdVmText = '重新部署';
                            // 显示销毁按钮
                            this.destroyStatus = true;
                            this.deployNum = 6;
                            //清除定时查询
                            clearInterval(this.queryStatus);
                            this.$Message.error({
                                content: message,
                                duration: 3,
                            });
                            this.getProjectInfo(); //查询错误信息
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }, 3000);
        },
        // 获取科研环境的部署状态
        getExperStatus() {
            selectStatus(this.ecId)
                .then(({ code, data, message }) => {
                    let { projectId, deployStatus: status } = data;
                    this.deployStatus = status;
                    this.proId = projectId;
                    this.detailParent.updateDetail({
                        deployStatus: this.deployStatus,
                        prjId: projectId,
                    });
                    if (this.proId) {
                        this.getProjectInfo();
                    }
                    // 新建   未部署
                    if (status === 0 || status === 10) {
                        // 按钮颜色 文字
                        this.btnType = 'primary';
                        this.detailParent.updateDetail({
                            generateImageList: [],
                        });
                    } else if (status === 3) {
                        // 成功
                        // 按钮颜色 文字
                        this.btnType = 'success';
                        this.createdVmText = '部署成功';
                        // 显示销毁按钮
                        this.destroyStatus = true;
                        this.getDestroyTimeInter();
                        this.showProgess = false;
                    } else if (status === 6) {
                        // 失败
                        // 按钮颜色 文字
                        this.btnType = 'primary';
                        this.createdVmText = '重新部署';
                        // 显示销毁按钮
                        this.destroyStatus = true;
                        this.showProgess = false;
                    } else if (status === 9) {
                        // 部署中
                        this.btnType = 'primary';
                        this.createdVmText = '部署中...';
                        this.creatLoading = true;
                        this.queryCreatedStatus();
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 销毁
        destroyExper() {
            destroyScientificProject(this.proId)
                .then(({ code, message }) => {
                    if (code == 1) {
                        this.proId = '';
                        this.createdLoad = false;
                        // 创建按钮
                        this.createdVmText = '部署科研环境';
                        this.btnType = 'primary';
                        // 销毁按钮
                        this.destroyStatus = false;
                        this.$Message.success({
                            content: message,
                            duration: 3,
                        });
                        this.deployNum = 10;
                        this.processText = '0%';
                        clearInterval(this.destroyInterval);
                        this.getExperStatus();
                        this.detailParent.updateDetail({ generateImageList: [] });
                    } else {
                        this.$Message.error(res.message);
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        //
        getDestroyTimeInter() {
            //              if(!this.destroyInterval){
            clearInterval(this.destroyInterval);
            this.queryDestroyTime();
            //一分钟矫正一次销毁时间
            this.destroyInterval = setInterval(() => {
                this.queryDestroyTime();
            }, 1000 * 60);
            //              }
        },
        // 获取销毁时间
        queryDestroyTime() {
            queryDestroyTime(this.proId)
                .then(({ code, data: { destroyTime } }) => {
                    if (code === 1) {
                        this.leftTime = destroyTime;
                        if (this.leftTime > 0) {
                            this.getTimes();
                        } else {
                            //                                window.close();
                            clearInterval(this.destroyInterval);
                        }
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getTimes() {
            clearTimeout(this.timeout);
            let leftTime = this.leftTime;
            if (leftTime > 0) {
                let h = Math.floor(leftTime / 1000 / 60 / 60);
                let m = Math.floor((leftTime / 1000 / 60) % 60);
                let s = Math.floor((leftTime / 1000) % 60);
                this.curTime = {
                    h: h < 10 ? '0' + h : h,
                    m: m < 10 ? '0' + m : m,
                    s: s < 10 ? '0' + s : s,
                };
                let _this = this;
                this.timeout = setTimeout(() => {
                    _this.leftTime = _this.leftTime - 1000;
                    _this.getTimes();
                }, 1000);
            } else {
                clearInterval(this.destroyInterval);
            }
        },
        //获取工程部署错误详情
        getProjectInfo() {
            return new Promise((resolve, reject) => {
                if (!this.proId) {
                    return;
                }
                queryProjectstatus(this.proId)
                    .then(({ code, attribute: { network, project } }) => {
                        if (code == 1) {
                            this.projectInfo = project;
                            this.errorMessage = project.errorMessage;
                            resolve(project);
                        } else if (data.code == -2) {
                            this.$Message.error('工程不存在');
                        } else {
                            this.$Message.error(data.message);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            });
        },
        getProjectDeployDetail() {
            this.deployErrorDetailModal = true;
            let deployId = this.projectInfo.deployId;
            let params = {
                pageIndex: 1,
                pageSize: 1000,
                status: 400,
            };
            getProjectDeployDetail(deployId, params)
                .then((data) => {
                    if (data.code == 1) {
                        this.errorDetailData = data.data.items;
                    } else {
                        this.errorDetailData = [];
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        getImageList() {
            if (this.proId) {
                this.$refs.imageList.getCreateImageList();
            }
        },
        getReplaceTotal(total) {
            this.replaceTotal = total;
            if (total > 0) {
                this.$emit('on-finish', true);
            }
        },
        gotoNextStep() {
            // this.$emit('changeStep', 2);
        },
        extendDestroyTime() {
            queryDestroyTime(this.proId)
                .then(({ code, data: { destroyTime } }) => {
                    if (data.code == 1) {
                        this.$Message.info(data.message);
                        this.getDestroyTimeInter();
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
    },
};
</script>
<style scoped>
.destoryTime {
    color: #db4747;
    font-weight: 700;
    /* position: absolute; */
    top: 0px;
    right: 30px;
}
</style>
